import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:photo_frame/net/model/asset_trans_model.dart';
import 'package:photo_frame/net/model/frame_folder_model.dart';
import 'package:photo_frame/net/model/frame_info_model.dart';
import 'package:photo_frame/provider/app_trans_asset_provider.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/utils/database_manager.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_asset_image_widget.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:provider/provider.dart';

class SendAssetPreviewListPage extends StatefulWidget {
  @override
  State<SendAssetPreviewListPage> createState() =>
      _SendAssetPreviewListPageState();
}

class _SendAssetPreviewListPageState extends State<SendAssetPreviewListPage> {
  SendAssetPreviewProvider provider = SendAssetPreviewProvider();

  @override
  void initState() {
    super.initState();
    provider.fetchAssets(
        AppAssetTransProvider.provider().transAssetData(key: "assetIds"));
  }

  @override
  void dispose() {
    super.dispose();
    provider.disposeControllers();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
        value: provider,
        child: Scaffold(
            appBar: commonAppBar(appLocalForContext(context).sendPreview,
                actions: [buildRightNavbarItem()]),
            body: Container(
                padding: EdgeInsets.only(top: 10),
                color: Color(0xffF2F2F2),
                child: SafeArea(child: Consumer<SendAssetPreviewProvider>(
                    builder: (context, provider, child) {
                  return SizedBox(
                    height: double.infinity,
                    width: double.infinity,
                    child: ListView.separated(
                        separatorBuilder: (context, index) {
                          return SizedBox(height: 10);
                        },
                        itemBuilder: (context, index) {
                          return buildPreviewItem(provider, index);
                        },
                        itemCount: provider.assetList.length),
                  );
                })))));
  }

  buildPreviewItem(SendAssetPreviewProvider provider, int index) {
    return Row(
      children: [
        SizedBox(width: 10),
        SizedBox(
          width: 90,
          height: 90,
          child: AppAssetImageWidget(
            onPreview: false,
            selected: false,
            key: ValueKey<int>(index),
            entity: provider.assetList[index],
            option: const ThumbnailOption(size: ThumbnailSize.square(200)),
          ),
        ),
        SizedBox(width: 10),
        Expanded(
            child: Container(
          height: 90,
          decoration: BoxDecoration(
              border: Border.all(width: 1, color: Color(0xffdddddd))),
          padding: EdgeInsets.only(left: 8, right: 8),
          child: TextField(
            controller: provider.controlerList[index],
            maxLines: 3,
            minLines: 1,
            style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
            textInputAction: TextInputAction.done,
            cursorColor: Colors.blueAccent,
            decoration: InputDecoration(
              hintMaxLines: 1,
              border: InputBorder.none,
              hintText: appLocalForContext(context).previewAssetDesc,
              hintStyle: TextStyle(
                color: Colors.grey,
                fontSize: 14,
              ),
            ),
            onChanged: (value) {
              provider.assetDescMap[provider.assetList[index].id] = value;
            },
          ),
        )),
        SizedBox(
          width: 10,
        )
      ],
    );
  }

  buildRightNavbarItem() {
    return CupertinoButton(
      padding: EdgeInsets.zero,
      onPressed: () async {
        FrameInfoModel? frame = AppAssetTransProvider.provider()
            .transAssetData<FrameInfoModel>(key: "frame");
        FrameFolderModel? folder = AppAssetTransProvider.provider()
            .transAssetData<FrameFolderModel>(key: "folder");
        if (frame?.frame_id == null || folder?.getOriginalName() == null) {
          return;
        }
        DateTime now = DateTime.now();
        // String date = DateFormat('yyyy/MM/dd').format(now);
        String uuid = "${now.millisecondsSinceEpoch}";
        List<AssetTransModel> assetTransList = provider.assetList.map((asset) {
          AssetTransModel model = AssetTransModel();
          model.toFrameId = frame?.frame_id;
          model.toFrameName = frame?.name;
          model.toFrameFolderName = folder?.getOriginalName();
          model.assetId = asset.id;
          model.markDesc = provider.assetDescMap[asset.id];
          model.batchId = uuid;
          model.transDate = "${now.millisecondsSinceEpoch}";
          return model;
        }).toList();
        for (var transModel in assetTransList) {
          await DatabaseManager.instance.create(transModel);
        }
        AppAssetTransProvider.provider().clearAllTransAssetBuffer();
        ARouter.instance.pagePopToRootThenPush("/sendAssetRecord");
      },
      child: actionTextWidget(appLocalForContext(context).next),
    );
  }
}

class SendAssetPreviewProvider extends ChangeNotifier {
  List<TextEditingController> controlerList = [];
  List<AssetEntity> assetList = [];
  Map<String, String> assetDescMap = {};
  fetchAssets(List<String>? assetIds) async {
    disposeControllers();
    if (assetIds == null || assetIds.isEmpty) {
      return;
    }
    for (String assetId in assetIds) {
      AssetEntity? asset = await AssetEntity.fromId(assetId);
      if (asset != null) {
        assetList.add(asset);
        TextEditingController c = TextEditingController();
        controlerList.add(c);
        assetDescMap[assetId] = "";
      }
    }
    notifyListeners();
  }

  disposeControllers() {
    for (TextEditingController c in controlerList) {
      c.dispose();
    }
    controlerList.clear();
  }
}
